import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimmer/shimmer.dart';
import 'package:sports_new/controller/expert/top/league_top_list_logic.dart';
import 'package:sports_new/entity/expert/expert_top_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/record/items/data_left_list.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import '../../../utils/mode_config.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/loading/shimmer_loading_widget.dart';
import '../items/expert_first_tag.dart';

class LeagueTopListView extends StatefulWidget {
  final int sportsId;
  final ScrollPhysics physics;
  final bool? onlySale;
  const LeagueTopListView(this.sportsId, {super.key, required this.physics, this.onlySale});

  @override
  State<LeagueTopListView> createState() => _LeagueTopListViewState();
}

class _LeagueTopListViewState extends State<LeagueTopListView> {
  late LeagueTopListLogic logic;

  @override
  void initState() {
    super.initState();
    logic =
        Get.put(LeagueTopListLogic(widget.sportsId), tag: '${widget.sportsId}');
    if(widget.onlySale != null) logic.onlySale = widget.onlySale!;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LeagueTopListLogic>(
      tag: '${widget.sportsId}',
      builder: (_) {
        return Column(
          children: [condition(), Expanded(child: body())],
        );
      },
    );
  }

  Widget condition() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          ...List.generate(
            logic.condition!.length,
            (index) => QkdButton(
              text: logic.condition![index].name,
              backgroundColor: logic.conditionIndex == index
                ? Colours.main
                : Colours.greyF7,
              textStyle: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
                color: logic.conditionIndex == index
                  ? Colours.white
                  : Colours.grey66
              ),
              width: 56,
              height: 24,
              onPressed: () => logic.onTapCondition(index)
            ).marginOnly(right: 8)
          ),
          const Spacer(),
          QkdButton(
            height: 24,
            widget: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  Utils.getImgPath(
                    logic.onlySale ? 'check.png' : 'uncheck.png'),
                  width: 14,
                  height: 14,
                ),
                const SizedBox(width: 2),
                QkdText(
                  '只看在售',
                  color: Colours.grey66,
                ),
              ]
            ),
            onPressed: logic.onTapFilter
          ),
        ],
      ),
    );
  }

  Widget body() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
          LoadingWidget<bool>(
            isLoading: logic.leagues == null,
            loading: SingleChildScrollView(
              child: ShimmerLoading(width: 75, height: Get.height,radius: 2,direction: ShimmerDirection.ttb,)
            ),
            data: logic.leagues?.length == 0,
            child: () => DataLeftList(
              logic.leagues!.map((e) => e.name!).toList(),
              logic.leagueIndex,
              ((p0) {
                logic.onSelectLeague(p0);
              }),
            ),
          ),
        Expanded(
          child: right()
        ),
      ],
    );
  }

  Widget right() {
    return LoadingWidget(
      isLoading: logic.list == null,
      loading: SingleChildScrollView(
        physics: widget.physics,
        child: Column(
          children: List.generate(
            20, (index) => shimmerItem()
          )
        ),
      ),
      data: logic.list?.length == 0,
      child: () => CustomScrollView(
        physics: widget.physics,
        slivers: [
          // const HeaderLocator.sliver(),
          SliverList.builder(
            itemBuilder: (context, index) {
              return cell(index);
            },
            itemCount: logic.list!.length,
          ),
          SliverToBoxAdapter(
            child: GestureDetector(
              onTap: () {
                Get.toNamed(
                  Routes.expertAll,
                  arguments: widget.sportsId == 1 ? 0 : 1
                );
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const QkdText(
                      '查看全部专家',
                      needCenter: true,
                      fontSize: 12,color: Colours.grey66
                    ),
                    Image.asset(
                      Utils.getImgPath('arrow_right_36.png'),
                      width: 12,
                    )
                  ],
                ),
              ),
            ),
          ),
          SliverToBoxAdapter(child: Container(height: 62))
        ],
      ),
    );
  }

  Widget cell(int index) {
    ExpertTopEntity data = logic.list![index];
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.fromLTRB(8, 14, 16, 14),
          child: Row(children: [
            if (index > 2)
              Container(
                width: 24,
                alignment: Alignment.center,
                child: QkdText('${index + 1}',
                    fontSize: 13
                ),
              )
            else
            Image.asset(
              Utils.getImgPath('expert_top${index+1}.png'),
              width: 24,
            ),
            const SizedBox(width: 8),
            ClipOval(
              child: CachedNetworkImage(
                imageUrl: data.userLogo ?? '',
                width: 32,
                height: 32,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Row(
                children: [
                  Flexible(
                    child: QkdText('${data.userName}',
                      maxLines: 1,
                    ),
                  ),
                  Container(width: 4),
                  if(ModeConfig.expertRecord && data.value.hasValue)
                    ExpertFirstTag(tag: data.value!),
                ],
              ),
            ),
            Container(width: 4),
            FocusButton(
              data.isFocus ?? 0,
              userId: data.userId,
              onTap: (p0) {
                data.isFocus = p0;
              },
            )
          ]),
        ).tap(() {
          Get.toNamed(Routes.userPage,
              arguments: data.userId, parameters: {'type': '1'});
        }),
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          color: Colours.greyEE,
          height: 0.5,
          width: double.infinity,
        )
      ],
    );
  }

  Widget shimmerItem(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.fromLTRB(8, 14, 16, 14),
          child: const Row(
              children: [
                SizedBox(width: 24+8),
                ShimmerLoading(width: 32, height: 32, shape: BoxShape.circle),
                SizedBox(width: 8),
                ShimmerLoading(width: 69, height: 19),
                Spacer(),
                ShimmerLoading(width: 56, height: 24,radius: 4)
              ]
          ),
        ),
        Divider(
            color: Colours.greyCC.withOpacity(0.2), height: 0.5
        ).paddingSymmetric(horizontal: 16)
      ],
    );
  }
}
